angular.module('furion.controllers.other', [])

# WelcomeCtrl
.controller 'WelcomeCtrl', ($scope, $state, $ImageCacheFactory, RemoteSrv, TouchAndGestureService, Toast) ->
  cacheImage = (images)->
    $ImageCacheFactory.Cache(images).then(()->
      console.log("Images done loading, total: "+images.length+" entries.")
    ,(failed)->
      console.log("An image filed: "+failed)
    )

  timeID = null
  getFrontImage = ()->
    images = ['img/welcome/before.png']

    # RemoteSrv.getFrontPicture().fail((err) ->
    #   console.log("ERR on fetching front picture, and fallback: " + err)
    # ).done((resp) ->
    #   if resp.status.success
    #     images = [resp.data] if resp.data? && resp.data != ""
    #     console.log("got images")
    #     console.log(images)
    #   else
    #     console.log("ERR on fetching front picture, and fallback: " + resp.status.msg)
    # ).always( ()->
    #   console.log("always here")

    # 等显示的图片已经准备好再 hide
    cacheImage(images).then ()->
      console.log("cache image finished")
      navigator.splashscreen.hide() if furion.utils.isDevice()

      $scope.imgurl = images[0]
      console.log("Using picture: #{$scope.imgurl}")

      clearInterval(timeID) if timeID
      timeID = setTimeout ->
        $scope.enterApp()
        # console.debug 'welcome'
      , 3000
    

  $scope.$on '$ionicView.enter', (event)->
    console.info "enter welcome"
    setTimeout ->
      getFrontImage()

  $scope.enterApp = ()->
    console.log("ENTER APP")
    clearInterval(timeID) if timeID

    $state.go 'newbie'
    # TouchAndGestureService.check(true)

# newbiectrl
.controller 'NewbieCtrl', ($scope, $ionicSlideBoxDelegate, $state)->
  $scope.first_open_imgs = [
    {img: 'img/welcome/01.jpg', text: '01'},
    {img: 'img/welcome/02.jpg', text: '02'},
    {img: 'img/welcome/03.jpg', text: '03'},
  ]

  $scope.$on '$ionicView.enter', (event, params)->
    # 如果是 app 环境，显示 welcome 页面
    # if device? || Config.debug
    # $scope.init()
    # else
    #   $state.go 'tab.fixed-gain-list'

  $scope.currentIndex = ()->
    index = $ionicSlideBoxDelegate.currentIndex()
    if index == $scope.first_open_imgs.length - 1
      $(".slider-pager").addClass('none')
    else
      $(".slider-pager").removeClass('none')
    index

  $scope.firstOpenOver = ()->
    # Storage.set(Storage.config.FirstOpen, true)
    $state.go 'app.home'

  return

# ResourceCtrl
.controller 'ResourceCtrl', ($scope, $rootScope, $stateParams, RemoteSrv, $sce, H5PostMessage, Config, Toast)->

  $scope.goBack = ()->
    $scope.iframe_url = null
    $rootScope.goBack(true)

  $scope.$on '$ionicView.enter', (event)->
    if $stateParams.url == null
      Toast.show '无效的链接'
      $scope.goBack()
      return
    $scope.title ||= $stateParams.title
    $scope.title ||= Config.vname
    $scope.iframe_url = $sce.trustAsResourceUrl $stateParams.url

    H5PostMessage.init $scope, window.frames[0], $scope.iframe_url
    return

  return

.controller 'ActivitiesCtrl', ($scope, $state, RemoteSrv)->
  $scope.curPage = 1
  $scope.maxPage = 1

  $scope.$on '$ionicView.enter', (event)->
    $scope.now_time = (new Date).getTime()
    # furion.storage.updateBadges('')
    $scope.refreshing()

  $scope.refreshing = ()->
    $scope.getActivityList(1)
    return

  $scope.getActivityList = (page)->
    RemoteSrv.getActivityList(page).done (resp)->
      $scope.curPage = resp.data.cur_page
      $scope.maxPage = resp.data.max_page
      $scope.list = if page == 1 then resp.data.list else $scope.list.concat resp.data.list

    .always ->
      $scope.$broadcast 'scroll.refreshComplete'
      $scope.$broadcast 'scroll.infiniteScrollComplete'

  $scope.goActivity = (activity)->
    page_url = activity.page_url
    if page_url? && page_url != ''
      if /^http/.test(page_url)
        $state.go 'resource', {title: activity.base.vname, url: page_url}
      else
        arr = page_url.split('(')
        state = arr[0]
        params = if arr.length > 1
          eval "(#{arr[1]}"
        else
          undefined
        console.debug params
        $state.go state, params
    return
  return


.controller 'PopupCtrl', ($scope, $ionicModal, $state, $stateParams, $ionicBackdrop) ->
  $scope.$on '$modal.enter', ()->
    console.log $scope
    $scope.cpm_config = $scope.modal_params.cpm_config
    $scope.imageId = $scope.modal_params.imageId
    $scope.imgurl = $scope.cpm_config.img_url

  $scope.closePad = ()->
    furion.storage.updatePopupMsg($scope.imageId) if $scope.cpm_config.show_type != "everystart"
    $ionicBackdrop.release()
    $scope.$emit "modals:close", {modal_name: 'pop_up'}

  $scope.open_url = (url)->
    $scope.closePad()
    window.location.assign("#/#{url}") if url
  return
